/**
 * The MIT License (MIT)
 * <p>
 * Copyright (c) 2018 恒宇少年
 * <p>
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 * <p>
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * <p>
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.gitee.hengboy.mybatis.enhance.key.generator;

import com.gitee.hengboy.mybatis.enhance.exception.EnhanceFrameworkException;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.minbox.framework.sequence.Sequence;
import org.springframework.util.ObjectUtils;

import java.util.Collection;

/**
 * The key generator for {@link Sequence}
 *
 * @author 恒宇少年
 * @since 1.1.5
 */
public class MinBoxSequenceKeyGenerator extends AbstractKeyGenerator {
    private static final int DEFAULT_DATA_CENTER = 1;
    private final Sequence sequence = new Sequence(DEFAULT_DATA_CENTER);

    @Override
    protected void batchProcessBefore(MappedStatement ms, Collection<Object> statementParameters) {
        String[] keyProperties = ms.getKeyProperties();
        if (ObjectUtils.isEmpty(keyProperties)) {
            throw new EnhanceFrameworkException("并未设置主键字段，无法根据主键策略生成对应的主键值.");
        }
        String pkProperty = keyProperties[0];
        Configuration configuration = ms.getConfiguration();
        for (Object parameter : statementParameters) {
            MetaObject metaObject = configuration.newMetaObject(parameter);
            setPkFieldValue(metaObject, pkProperty, String.valueOf(sequence.nextId()));
        }
    }
}
